if exists (select 1
          from sysobjects
          where  id = object_id('bd_proc_sys_getMaxId')
          and type in ('P','PC'))
   drop procedure bd_proc_sys_getMaxId
go


CREATE PROCEDURE bd_proc_sys_getMaxId
    @classId INT,  
    @interId  INT OUTPUT,  
    @incrementValue INT = 1  
AS  

    DECLARE @tableName VARCHAR (50)

    SELECT @tableName=tableName FROM bd_sys_itemClass WHERE classId=@classId

    BEGIN TRANSACTION  
      
    UPDATE bd_sys_maxId SET maxId = maxId WHERE tableName = @tableName  
      
    IF EXISTS ( SELECT maxId FROM bd_sys_maxId WHERE tableName = @tableName)  
    BEGIN  
        UPDATE bd_sys_maxId SET maxId = maxId + @incrementValue WHERE tableName = @tableName  
          
        SELECT @interId = maxId - @incrementValue + 1 FROM bd_sys_maxId WHERE tableName = @tableName  
    END  
    ELSE  
    BEGIN  
        INSERT INTO bd_sys_maxId(tableName, maxId) VALUES (@tableName, 999 + @incrementValue)  
        SELECT @interId = 1000  
    END  
    IF @@ERROR = 0  
        COMMIT TRANSACTION  
    ELSE  
    BEGIN  
        ROLLBACK TRANSACTION  
        SELECT @interId = -1  
    END  

    RETURN @interId
